import dayjs from "dayjs";
import { getItem } from "./localStorage";
import { getToken } from "./auth";
import env from "./env";

// 根据shopId返回对应的店名
// id：1---西安   2---陕工院
export const shopIdName = (id = 1) => {
  return id == 1 ? "时光锦汉服体验店" : id == 2 ? "陕西工院汉服体验" : "";
};

// 返回多少时间前
export const timeInterval = (timesData: number) => {
  //如果时间格式是正确的，那下面这一步转化时间格式就可以不用了
  var dateBegin = timesData; //将-转化为/，使用new Date
  var dateEnd = new Date(); //获取当前时间
  var dateDiff = Math.abs(dateEnd.getTime() - dateBegin); //时间差的毫秒数
  var yearDiff = Math.floor(dateDiff / (24 * 3600 * 1000 * 365));
  var dayDiff = Math.floor(dateDiff / (24 * 3600 * 1000)); //计算出相差天数
  var leave1 = dateDiff % (24 * 3600 * 1000); //计算天数后剩余的毫秒数
  var hours = Math.floor(leave1 / (3600 * 1000)); //计算出小时数
  //计算相差分钟数
  var leave2 = leave1 % (3600 * 1000); //计算小时数后剩余的毫秒数
  var minutes = Math.floor(leave2 / (60 * 1000)); //计算相差分钟数
  //计算相差秒数
  var leave3 = leave2 % (60 * 1000); //计算分钟数后剩余的毫秒数
  var seconds = Math.round(leave3 / 1000);
  var timesString = "";
  if (yearDiff != 0) {
    timesString = yearDiff + "年前";
  } else if (yearDiff == 0 && dayDiff != 0) {
    timesString = dayDiff + "天前";
  } else if (dayDiff == 0 && hours != 0) {
    timesString = hours + "小时前";
  } else if (hours == 0 && minutes != 0) {
    timesString = minutes + "分钟前";
  } else if (minutes == 0 && seconds < 60) {
    timesString = "刚刚";
  }
  return timesString;
};

// 时间戳转日期
export const parseTime = (time, pattern) => {
  if (arguments.length === 0 || !time) {
    return null;
  }
  const format = pattern || "{y}-{m}-{d} {h}:{i}:{s}";
  let date;
  if (typeof time === "object") {
    date = time;
  } else {
    if (typeof time === "string" && /^[0-9]+$/.test(time)) {
      time = parseInt(time);
    } else if (typeof time === "string") {
      time = time
        .replace(new RegExp(/-/gm), "/")
        .replace("T", " ")
        .replace(new RegExp(/\.[\d]{3}/gm), "");
    }
    if (typeof time === "number" && time.toString().length === 10) {
      time = time * 1000;
    }
    date = new Date(time);
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay(),
  };
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key];
    // Note: getDay() returns 0 on Sunday
    if (key === "a") {
      return ["日", "一", "二", "三", "四", "五", "六"][value];
    }
    if (result.length > 0 && value < 10) {
      value = "0" + value;
    }
    return value || 0;
  });
  return time_str;
};

// 汉字正则（必须为中文）
export const chineseReg = (chinese: string) => {
  // 中文正则
  const reg = /^([\u4E00-\u9FA5])*$/;
  return reg.test(chinese);
};

// 手机号正则
export const phoneReg = (phone: number) => {
  const reg = /^1[3|4|5|6|7|8|9]\d{9}$/;
  return reg.test(phone);
};

// alert弹框
// 为什么封装？因为默认需要写过多的配置项才可以达成效果，这里做一封装
// 由于alert是window上的一个方法所以这里用大写A代替a
export const Alert = (
  title: string,
  icon: string = "none",
  duration: number = 1500,
  mask: boolean = false
) => {
  let duration_ = duration != 0 ? 1500 : 600000;

  console.log("duration____", duration_);

  uni.showToast({
    title, // 弹框标题
    icon, // icon图标（默认为none）
    duration: duration_, // 执行多少秒（默认1500ms）
    mask, // 是否显示透明蒙层，防止触摸穿透，默认：false
  });
};

// 隐藏消息提示框
export const unAlert = () => {
  uni.hideToast();
};

/**
都一样返回true，反之
示例
  isAllElementsSame([200, 200, 200])    // true
  isAllElementsSame([200, 300, 200])    // false
*/
export const isAllElementsSame = (arr) => {
  const firstElement = arr[0];

  // 检查所有元素是否与第一个元素相同
  return arr.every((element) => element === firstElement);
};

// 预览图片（1张）
export const previewImage = (url) => {
  uni.previewImage({
    urls: Array(url),
    success(res) {
      // console.log("res：", res);
    },
  });
};

// 预览图片（2张及以上）
export const previewImageList = (urlList) => {
  uni.previewImage({
    urls: urlList,
    success(res) {
      // console.log("res：", res);
    },
  });
};
